<?php

namespace App\Console\Commands;

use App\GatewayWorker\Events;
use Illuminate\Console\Command;
use GatewayWorker\BusinessWorker;
use GatewayWorker\Gateway;
use GatewayWorker\Register;
use Workerman\Worker;


class GatewayWorkerServer extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'workerman {action} {--d}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Start a Workerman server.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    private $localIp = '127.0.0.1';
    private $registerPort = '1236';
    private $workerPort = '3456';
    private $startGateway = true;
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        //
        global $argv;
        $action = $this->argument('action');

        $argv[0] = 'artisan workman';
        $argv[1] = $action;
        $argv[2] = $this->option('d') ? '-d' : '';   //必须是一个-，上面定义命令两个--，后台启动用两个--

        $this->localIp = env('WORKERMAN_LOCAL_IP', '127.0.0.1');
        $this->registerPort = env('WORKERMAN_REGISTER_PORT', '1236');
        $this->registerIp = env('WORKERMAN_REGISTER_IP', '127.0.0.1');
        $this->workerPort = env('WORKERMAN_WORKER_PORT', '3456');
        $this->startGateway = $this->localIp === $this->registerIp;

        $this->start();
    }
    private function start()
    {
        $this->startGateway && $this->startGateWay();
        $this->startBusinessWorker();
        $this->startRegister();
        Worker::runAll();
    }

    private function startBusinessWorker()
    {
        $worker                  = new BusinessWorker();
        $worker->name            = 'BusinessWorker';
        $worker->count           = 2;
        $worker->registerAddress = $this->registerIp.':'.$this->registerPort;
        $worker->eventHandler    = Events::class;
    }

    private function startGateWay()
    {
        $gateway = new Gateway("websocket://".$this->localIp.':'.$this->workerPort);
        $gateway->name                 = 'Sxcx-Lichao';
        $gateway->count                = 1;
        $gateway->lanIp                = $this->localIp;
        $gateway->startPort            = env('WORKERMAN_START_PORT',6100);
        $gateway->pingInterval         = 30;
        $gateway->pingNotResponseLimit = 0;
        $gateway->pingData             = '{"type":"ping"}';
        $gateway->registerAddress      = $this->registerIp.':'.$this->registerPort;
    }

    private function startRegister()
    {
        new Register('text://'.$this->registerIp.':'.$this->registerPort);
    }
}
